package com.uenpay.oem.ui.auth;

import android.content.Intent;
import android.os.Bundle;
import android.view.Display;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.socks.library.KLog;
import com.uenpay.im.utilities.Toasts;
import com.uenpay.oem.R;
import com.uenpay.oem.data.bean.UserIdCardInfo;
import com.uenpay.oem.widget.RotateTextView;
import com.uenpay.oem.widget.camera.CameraHelper;
import com.uenpay.oem.widget.camera.MaskSurfaceView;
import com.uenpay.oem.widget.camera.OnCaptureCallback;
import com.uenpay.res.widget.dialog.LoadDialog;
import com.uenpay.util.app.base.BaseActivity;

import butterknife.BindView;
import butterknife.OnClick;

public class AuthCameraActivity extends BaseActivity implements AuthCameraContract.View, OnCaptureCallback {

    private static final String TAG = AuthCameraActivity.class.getSimpleName();

    public static final int TAKE_PHOTO_POSITIVE = 0; //身份证正面照
    public static final int TAKE_PHOTO_BACK = 1; //身份证反面照


    @BindView(R.id.iv_people_sample)
    ImageView ivPeopleSample;
    @BindView(R.id.tv_recognition)
    RotateTextView tvRecognition;
    @BindView(R.id.iv_remake)
    ImageView ivRemake;
    @BindView(R.id.tv_remake)
    RotateTextView tvRemake;
    @BindView(R.id.surface_view)
    MaskSurfaceView surfaceview;
    @BindView(R.id.bnToggleCamera)
    ImageView bnToggleCamera;
    @BindView(R.id.bnCapture)
    ImageView bnCapture;
    @BindView(R.id.tv_tip_right)
    TextView tvTipRight;
    @BindView(R.id.tv_tip_left)
    TextView tvTipLeft;
    @BindView(R.id.iv_close)
    ImageView ivClose;

    private int bncaptureWidth = 0;
    private int bnToggleWidth = 0;

    private static final int SHOWPIC_CODE = 100;

    private boolean frontCamera = false;

    //照相按钮状态 0：照相 1：识别
    private int takePhotoFlag = 0;

    private int takePhotoType;

    private byte[] mPhotoData;

    private AuthCameraContract.Presenter mCameraPresenter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        isFullScreen = true;
        isHideStatuBar = true;
        super.onCreate(savedInstanceState);
    }

    @Override
    public View bindView() {
        return null;
    }

    @Override
    public int bindLayout() {
        return R.layout.activity_auth_camera;
    }

    @Override
    public void initView(View view) {
        if (getIntent() != null) {
            takePhotoType = getIntent().getIntExtra("type", TAKE_PHOTO_POSITIVE);
        }
        setMarkSize();
        setPresenter(null);
        CameraHelper.getInstance().needAutoFocuse(this);
        CameraHelper.getInstance().setFlashlight(CameraHelper.Flashlight.OFF);

        switch (takePhotoType) {
            case TAKE_PHOTO_POSITIVE:
                tvTipRight.setText("拍摄身份证正面照，尝试对齐边缘");
                break;
            case TAKE_PHOTO_BACK:
                tvTipRight.setText("拍摄身份证反面照，尝试对齐边缘");
                ivPeopleSample.setVisibility(View.GONE);
                break;
            default:
                break;
        }
    }

    @Override
    public void showLoading() {
        LoadDialog.show(this, "正在识别...");
    }

    @Override
    public void dismissLoading() {
        LoadDialog.dismiss(this);
    }

    @Override
    public void setPresenter(Object presenter) {
        mCameraPresenter = new AuthCameraPresenter(this);
    }

    @Override
    public void showToast(String msg) {
        Toasts.shortToast(this, msg);
    }

    @Override
    public void recognitionResult(UserIdCardInfo info) {
        Intent intent = new Intent();
        intent.putExtra("idcard", info);
        intent.putExtra("type", takePhotoType);
        setResult(RESULT_OK, intent);
        finish();
    }

    @OnClick(R.id.iv_remake)
    @Override
    public void remake() {
        if (!bnCapture.isEnabled()) {
            bnCapture.setEnabled(true);
        }
        takePhotoFlag = 0;
        stopPreview(false);
    }

    @OnClick(R.id.bnCapture)
    public void takePhoto() {
        bnCapture.setEnabled(false);
        bnCaptureClicked();
    }
    @OnClick(R.id.iv_close)
    public void close(){
        finish();
    }

    private void setMarkSize() {
        Display display = getWindowManager().getDefaultDisplay();
        int w = display.getWidth();
        int h = display.getHeight();
        bnToggleCamera.measure(w, h);
        bnCapture.measure(w, h);
        bncaptureWidth = bnCapture.getMeasuredWidth();
        bnToggleWidth = bnToggleCamera.getMeasuredWidth();
        //设置矩形区域大小
        int height = h - 3 * bncaptureWidth;
        int width = 2 * (height) / 3;
        surfaceview.setMaskSize(width, height, w, h);
    }

    @Override
    public void onCapture(boolean success, byte[] data) {
        KLog.d("take photo:" + success);
        bnCapture.setEnabled(true);
        if (success) {
            mPhotoData = data;
            stopPreview(true);
            takePhotoFlag = 1;
        } else {
            mPhotoData = null;
            Toasts.shortToast(this, "拍照失败");
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == SHOWPIC_CODE && resultCode == RESULT_OK) {
            setResult(RESULT_OK);
            finish();
        }
    }

    private void bnCaptureClicked() {
        if (takePhotoFlag == 0) {
            CameraHelper.getInstance().tackPicture(this);
        } else {
            if (mPhotoData != null && mCameraPresenter != null) {
                mCameraPresenter.recognition(mPhotoData, takePhotoType);
            } else {
                showToast("请重新拍照");
            }
        }
    }

    private void stopPreview(boolean isStop) {
        if (isStop) {
            ivPeopleSample.setVisibility(View.GONE);
            tvTipRight.setVisibility(View.GONE);
            tvTipLeft.setVisibility(View.GONE);
            ivRemake.setVisibility(View.VISIBLE);
            tvRemake.setVisibility(View.VISIBLE);
            tvRecognition.setVisibility(View.VISIBLE);
            bnCapture.setImageDrawable(getResources().getDrawable(R.drawable.icon_capture_confirm));
            CameraHelper.getInstance().stopPreview();
        } else {
            CameraHelper.getInstance().startPreview();
            if (takePhotoType == TAKE_PHOTO_POSITIVE) {
                ivPeopleSample.setVisibility(View.VISIBLE);
            }
            tvTipRight.setVisibility(View.VISIBLE);
            tvTipLeft.setVisibility(View.VISIBLE);
            ivRemake.setVisibility(View.GONE);
            tvRemake.setVisibility(View.GONE);
            tvRecognition.setVisibility(View.GONE);
            bnCapture.setImageDrawable(getResources().getDrawable(R.drawable.icon_capture_take_pic));
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        bnCapture.setEnabled(true);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
//        LoadDialog.dismiss(this);
        CameraHelper.getInstance().destory();
    }
}
